import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:guessit/computers_num.dart';
import 'package:guessit/history_page.dart';
import 'package:guessit/info_page.dart';
import 'package:guessit/result.dart';
import 'package:guessit/reusablenum_card.dart';
import 'constants.dart';
import 'customalert.dart';
import 'roundnumbutton.dart';
import 'result.dart';

class GuessItPage extends StatefulWidget {
  GuessItPage({this.title});
  final String title;

  @override
  _GuessItPageState createState() => _GuessItPageState();
}

class _GuessItPageState extends State<GuessItPage> {
  bool isGameFinnished = false;
  Queue<Result> resulta = new Queue<Result>();
  List<String> mainNums = [" ", " ", " ", " "];
  String result = "";

  int emptySlot() {
    int slot = 4;
    for (var i = 0; i < mainNums.length; i++) {
      if (mainNums[i] == " ") {
        slot = i;
        return slot;
      }
    }
    return slot;
  }

  void addNumber({int empty_place, int num}) {
    if (empty_place == 0 && num == 0) {
      CustomAlert cstdial =
          CustomAlert('“0”不能作为第一个数字', '提示', '知道了', this.context);

      showDialog(
        context: this.context,
        builder: (BuildContext context) {
          return cstdial.dialog;
        },
      );
    } else {
      mainNums[empty_place] = num.toString();
    }
  }

  List<int> com = Computers_Num().random();

  List<int> restart(bool isgamefinnished) {
    if (isgamefinnished == true) {
      resulta.clear();
      com = Computers_Num().random();
      CustomAlert cstdial = CustomAlert('成功！密码正确', '提示', '确定', this.context);

      showDialog(
        context: this.context,
        builder: (BuildContext context) {
          return cstdial.dialog;
        },
      );
      result = " ";
      mainNums = [" ", " ", " ", " "];
      isgamefinnished = false;
      return com;
    }
  }

  String check_numbers(List<int> com, List<String> inp) {
    try {
      int pozitive_count = 0, negative_count = 0;
      String result = " ";
      List<int> inp_digits = inp.map(int.parse).toList();

      if (Computers_Num().inputchecker(inp) == false) {
        CustomAlert cstdial =
            CustomAlert('你输入了相同的数字', '提示', '知道了', this.context);

        showDialog(
          context: this.context,
          builder: (BuildContext context) {
            return cstdial.dialog;
          },
        );
      } else {
        for (int i = 0; i < inp_digits.length; i++) {
          for (int j = 0; j < inp_digits.length; j++) {
            if (inp_digits[i] == com[j] && i == j) {
              pozitive_count++;
            } else if (inp_digits[i] == com[j] && i != j) {
              negative_count++;
            }
          }
        }

        if (pozitive_count != 0 && negative_count != 0) {
          result = "猜中 $pozitive_count 个数字\n存在 $negative_count 个位置不准确的数字";
        } else if (pozitive_count == 0 && negative_count != 0) {
          result = "存在 $negative_count 个位置不准确的数字";
        } else if (pozitive_count != 0 && negative_count == 0) {
          if (pozitive_count == 4) {
            result = "成功";
          } else {
            result = "猜中 $pozitive_count 个数字";
          }
        } else if (pozitive_count == 0 && negative_count == 0) {
          result = "全部错误";
        }

        return result;
      }
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xFF2F73E8),
        leading: IconButton(
          icon: Icon(Icons.info_outline),
          onPressed: () {
            Navigator.push(
                context, MaterialPageRoute(builder: (context) => InfoPage()));
          },
        ),
        elevation: 0,
        actions: [
          IconButton(
            icon: Icon(
              Icons.history,
            ),
            onPressed: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => HistoryPage(resulta)));
            },
          ),
        ],
      ),
      body: Container(
        decoration: BoxDecoration(
          color: Color(0xFF2F73E8),
        ),
        child: Column(
          children: [
            Expanded(
              child: Container(
                padding: EdgeInsets.all(55),
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('assets/img/screen.png'),
                    fit: BoxFit.fill,
                  ),
                ),
                child: Row(
                  children: [
                    Flexible(
                      child: ConstrainedBox(
                        constraints: BoxConstraints(maxHeight: 100),
                        child: ReusableNumCard(
                          colour: kActiveCardColour,
                          cardChild: Center(
                            child: Text(
                              mainNums[0],
                              textAlign: TextAlign.center,
                              style: kLabelTextStyle,
                            ),
                          ),
                        ),
                      ),
                    ),
                    Flexible(
                      child: ConstrainedBox(
                        constraints: BoxConstraints(maxHeight: 100),
                        child: ReusableNumCard(
                          colour: kActiveCardColour,
                          cardChild: Center(
                            child: Text(
                              mainNums[1],
                              textAlign: TextAlign.center,
                              style: kLabelTextStyle,
                            ),
                          ),
                        ),
                      ),
                    ),
                    Flexible(
                      child: ConstrainedBox(
                        constraints: BoxConstraints(maxHeight: 100),
                        child: ReusableNumCard(
                          colour: kActiveCardColour,
                          cardChild: Center(
                            child: Text(
                              mainNums[2],
                              textAlign: TextAlign.center,
                              style: kLabelTextStyle,
                            ),
                          ),
                        ),
                      ),
                    ),
                    Flexible(
                      child: ConstrainedBox(
                        constraints: BoxConstraints(maxHeight: 100),
                        child: ReusableNumCard(
                          colour: kActiveCardColour,
                          cardChild: Center(
                            child: Text(
                              mainNums[3],
                              textAlign: TextAlign.center,
                              style: kLabelTextStyle,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Column(
              children: [
                Text(
                  (() {
                    if (result == null) {
                      return " ";
                    } else {
                      return result;
                    }
                  }()),
                  style: kResultTextStyle,
                ),
                Container(
                  margin: EdgeInsets.fromLTRB(0, 20, 0, 40),
                  width: 60,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    color: Color(0xFCFF004C),
                  ),
                  child: Center(
                    child: IconButton(
                      icon: Icon(
                        Icons.delete,
                        size: 32,
                        color: Color(0xFCFFDBE7),
                      ),
                      onPressed: () {
                        setState(() {
                          if (mainNums.isEmpty == false) {
                            mainNums = [" ", " ", " ", " "];
                          }
                        });
                      },
                    ),
                  ),
                ),
                Table(
                  defaultVerticalAlignment: TableCellVerticalAlignment.middle,
                  defaultColumnWidth: FlexColumnWidth(1),
                  children: [
                    TableRow(
                      children: [
                        Padding(
                          padding: EdgeInsets.all(12.5),
                          child: RoundNumButton(
                            num: 0,
                            onPress: () {
                              setState(() {
                                if (emptySlot() < 4) {
                                  int slot = emptySlot();
                                  addNumber(empty_place: slot, num: 0);
                                }
                              });
                            },
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.all(12.5),
                          child: RoundNumButton(
                            num: 1,
                            onPress: () {
                              setState(() {
                                if (emptySlot() < 4) {
                                  int slot = emptySlot();
                                  addNumber(empty_place: slot, num: 1);
                                }
                              });
                            },
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.all(12.5),
                          child: RoundNumButton(
                            num: 2,
                            onPress: () {
                              setState(() {
                                if (emptySlot() < 4) {
                                  int slot = emptySlot();
                                  addNumber(empty_place: slot, num: 2);
                                }
                              });
                            },
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.all(12.5),
                          child: RoundNumButton(
                            num: 3,
                            onPress: () {
                              setState(() {
                                if (emptySlot() < 4) {
                                  int slot = emptySlot();
                                  addNumber(empty_place: slot, num: 3);
                                }
                              });
                            },
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.all(12.5),
                          child: RoundNumButton(
                            num: 4,
                            onPress: () {
                              setState(() {
                                if (emptySlot() < 4) {
                                  int slot = emptySlot();
                                  addNumber(empty_place: slot, num: 4);
                                }
                              });
                            },
                          ),
                        ),
                      ],
                    ),
                    TableRow(children: [
                      Padding(
                        padding: EdgeInsets.all(12.5),
                        child: RoundNumButton(
                          num: 5,
                          onPress: () {
                            setState(() {
                              if (emptySlot() < 4) {
                                int slot = emptySlot();
                                addNumber(empty_place: slot, num: 5);
                              }
                            });
                          },
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.all(12.5),
                        child: RoundNumButton(
                          num: 6,
                          onPress: () {
                            setState(() {
                              if (emptySlot() < 4) {
                                int slot = emptySlot();
                                addNumber(empty_place: slot, num: 6);
                              }
                            });
                          },
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.all(12.5),
                        child: RoundNumButton(
                          num: 7,
                          onPress: () {
                            setState(() {
                              if (emptySlot() < 4) {
                                int slot = emptySlot();
                                addNumber(empty_place: slot, num: 7);
                              }
                            });
                          },
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.all(12.5),
                        child: RoundNumButton(
                          num: 8,
                          onPress: () {
                            setState(() {
                              if (emptySlot() < 4) {
                                int slot = emptySlot();
                                addNumber(empty_place: slot, num: 8);
                              }
                            });
                          },
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.all(12.5),
                        child: RoundNumButton(
                          num: 9,
                          onPress: () {
                            setState(() {
                              if (emptySlot() < 4) {
                                int slot = emptySlot();
                                addNumber(empty_place: slot, num: 9);
                              }
                            });
                          },
                        ),
                      ),
                    ]),
                  ],
                ),
              ],
            ),
            InkWell(
              onTap: () {
                setState(() {
                  result = check_numbers(com, mainNums);
                  resulta.addFirst(Result(mainNums, result));
                });
                if (result != "成功") {
                  mainNums = [
                    " ",
                    " ",
                    " ",
                    " "
                  ]; // burda eğer hepsini bilmediği zaman baştaki 4 numarayı boşluk atıyorum
                } else if (result == "成功") {
                  isGameFinnished = true;
                  com = restart(isGameFinnished);
                }
              },
              child: Container(
                width: 200,
                height: 70,
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('assets/img/try.png'),
                  ),
                ),
              ),
            ),
            SizedBox(height: MediaQuery.of(context).padding.bottom + 15),
          ],
        ),
      ),
    );
  }
}
